<template>
	<view class="container">
		<!-- 		<discountNotice /> -->
		<view class="content">
			<view class="mer">
				<view class="icon-out" :style="{ background: color }">
					<image src="../../static/mer.svg" class="icon" mode="widthFix" />
				</view>
				<view class="name">{{ shopName }}</view>
			</view>
			<view class="input">
				<view class="label">消费金额</view>
				<view class="count">
					<view class="mone-icon">￥</view>
					<view class="money">{{ money }}</view>
					<view class="money-label">
						<view class="sep" v-show="sep" :style="{ background: color }" />
					</view>
				</view>
			</view>
		</view>
		<view class="bottom">
			<view class="phone" @click="call">联系合作</view>
			<view class="grid">
				<view class="submit" @click="payNow" :style="{ background: payNowActived ? color : unColor }">
					<view class="inner">
						<view>确认</view>
						<view>支付</view>
					</view>
				</view>
				<view :class="tapKeyword == '1' ? 'item tapped' : 'item'" @click="tap('1')">1</view>
				<view :class="tapKeyword == '2' ? 'item tapped' : 'item'" @click="tap('2')">2</view>
				<view class="item" :class="tapKeyword == '3' ? 'item tapped' : 'item'" @click="tap('3')">3</view>
				<view class="item back-item" :class="tapKeyword == 'back' ? 'item tapped' : 'item'" @click="tap('back')">
					<image src="../../static/back.svg" class="back-icon" mode="widthFix" />
				</view>
				<view class="item" :class="tapKeyword == '4' ? 'item tapped' : 'item'" @click="tap('4')">4</view>
				<view class="item" :class="tapKeyword == '5' ? 'item tapped' : 'item'" @click="tap('5')">5</view>
				<view class="item" :class="tapKeyword == '6' ? 'item tapped' : 'item'" @click="tap('6')">6</view>
				<view class="item" :class="tapKeyword == '7' ? 'item tapped' : 'item'" @click="tap('7')">7</view>
				<view class="item" :class="tapKeyword == '8' ? 'item tapped' : 'item'" @click="tap('8')">8</view>
				<view class="item" :class="tapKeyword == '9' ? 'item tapped' : 'item'" @click="tap('9')">9</view>
				<view class="zero item" :class="tapKeyword == '0' ? 'item tapped' : 'item'" @click="tap('0')">0</view>
				<view class="item" :class="tapKeyword == '.' ? 'item tapped' : 'item'" @click="tap('.')">.</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { setBusId } from '../../store/business';
import { setDiscountList, setBalance } from '../../store/user';
import http from '../../vendor/http';
import useGlobal from '../../store/global';
import discountNotice from '../../components/discountNotice.vue';
import { state, setToken } from '../../store/user';

const global = useGlobal();

let color = ref('#55BA36');
let unColor = ref('#C0EAB8');

// #ifdef MP-ALIPAY
color.value = '#3874F6';
//#endif

// #ifdef MP-ALIPAY
unColor.value = '#BDD5FB';
//#endif

const payNowActived = ref(true);

const call = () => {
	uni.makePhoneCall({
		phoneNumber: global.getServicePhone
	});
};

const money = ref('1000'); // 单笔最大2000  小数点最小后2位
const maxSize = 9999;
const sep = ref(false);
const tapKeyword = ref('');
let shopName = ref('');

let payAmount = '';

let busId = 0;
const login = (url: string, cal: Function = () => {}) => {
	uni.showLoading();
	uni.login({
		success: (res: any) => {
			uni.hideLoading();
			// 调用登录接口
			const d = { code: res.code };
			http.fetchGet(url, d).then((res: any) => {
				cal(res);
			});
		},
		fail: (res: any) => {
			console.log(res);
		}
	});
};

onLoad((query: any) => {
	// 测试
	query.q = 'http://www.qq.com/全聚德烤鸭/123456'; //  其中http为业务域名   全聚德烤鸭为店铺名称  12345为子商户号
	const q = decodeURIComponent(query.q); // 获取到二维码原始链接内容
	const arr = q.split('/');
	busId = parseInt(arr[arr.length - 1]);
	setBusId(busId);
	shopName.value = arr[arr.length - 2];

	if (!state.token) {
		// 微信登录
		// #ifdef MP-WEIXIN
		login('/api/wxlogin', ({ token }) => {
			state.token = token;
			// setToken(token)
		});
		//#endif
		// #ifdef MP-ALIPAY
		login('/api/alilogin', ({ token }) => {
			state.token = token;
			// setToken(token)
		});
		//#endif
	}

	if (!global.getServicePhone) {
		http.fetchGet('/api/sysInfo').then((res: any) => {
			global.setServicePhone(res.phone);
		});
	}
});

watch(money, () => {
	const str = money.value.replace(/\.$/, ''); // 去除末尾的点号
	if (str != '' && str != '0' && str != '0.0' && str != '0.00') {
		payNowActived.value = true;
	} else {
		payNowActived.value = false;
	}
});

// 输入光标闪烁功能
setInterval(() => {
	sep.value = !sep.value;
}, 450);

// 点击键盘震动及背景灰色功能
const tap = (keyword: string) => {
	// 振动手机，持续200毫秒
	// uni.vibrateShort();
	tapKeyword.value = keyword;
	setTimeout(() => {
		tapKeyword.value = '';
	}, 200);
	switch (keyword) {
		case 'back':
			money.value = money.value.slice(0, -1);
			// 回退
			break;
		case '.':
			// 小数点
			// 判断是否已经含有小数点 如果有则不添加
			if (money.value.indexOf('.') > -1) {
				break;
			} else if (!money.value) {
				money.value += '0' + keyword;
			} else {
				money.value += keyword;
			}

			break;
		default:
			// 如果第一位是0 则下一位不能是0
			if (money.value == '0') {
				break;
			}
			// 判断小数点后是否已有两位 若有则不添加
			let regex = /^\d+\.\d{2}$/;
			if (regex.test(money.value)) {
				break;
			}
			// 判断是否到达单笔限额
			if (parseFloat(money.value + keyword) > maxSize) {
				break;
			}
			money.value += keyword;
			break;
	}
};
let reqStatusInter = null;
const pay = (d: any) => {
	console.log(d)
	uni.getProvider({
		service: 'payment',
		success: (res: any) => {
			const provider = res.provider;
			const success = () => {
				money.value = '';
				uni.navigateTo({
					url: 'pages/index/success'
				});
			};

			//  成功获取支付请求参数
			const func = () => {
				// 轮询验证订单状态

				reqStatusInter = setTimeout(() => {
					http.fetchGet(`/api/order_status/${d.inner_trade_no}`).then((res: any) => {
						switch (res.status) {
							case 0:
							case 1:
								reqStatusInter && func();
								break;
							case 2:
								// 成功

								uni.redirectTo({
									url: `/pages/index/success?amount=${payAmount}`
								});

								break;
							case 3:
								// 关闭
								uni.showToast({
									title: '支付失败',
									icon: 'none'
								});
								clearTimeout(reqStatusInter);
								reqStatusInter = null;
								break;
						}
					});
				}, 1500);
			};
			func();
 

			uni.requestPayment({
				provider: provider,
				orderInfo: d.orderInfo, //微信、支付宝订单数据 【注意微信的订单信息，键值应该全部是小写，不能采用驼峰命名】
				timeStamp: d.timestamp,
				nonceStr: d.nonce_str,
				package: d.package,
				signType: d.sign_type,
				paySign: d.pay_sign,
				// 异步通信获取结果
				// success: (res) => {
				// 		// #ifdef MP-WEIXIN
				// 		// // 跳转成功页
				// 		// uni.redirectTo({
				// 		// 	url:`/pages/index/success?amount=${payAmount}`
				// 		// })
				// 				//#endif
				// 						// #ifdef MP-ALIPAY
				// 							//#endif
				// 	// console.log("支付成功")

				// },
				fail: (res) => {
					// 用户取消支付  订单无效取消轮询访问
					console.log('客户取消支付');
					console.log(res);
				}
			});
		},
		fail: () => {
			console.log('失败');
		}
	});
};

const payNow = () => {
	if (!payNowActived.value) return;
	const v = formatMoney();

	payAmount = v;
	// 微信
	// #ifdef MP-WEIXIN
	// 创单
	http.fetchPost('/api/createOrder/wx', { code: busId, amount: v }).then((res: any) => {
		// 支付
		// delete res.code;
		pay(res);
	});

	//#endif

	// 支付宝
	// #ifdef MP-ALIPAY
	// 创单
	http.fetchPost('/api/createOrder/alipay', { code: busId, amount: v }).then((res: any) => {
		// 支付
		res.orderInfo = res.trade_no
		// delete res.code;
		// delete res.trade_no;
		pay(res);
	});
	//#endif
};

const formatMoney = () => {
	// 解析为浮点数
	let num = parseFloat(money.value);

	// 如果无效则返回原始字符串
	if (isNaN(num)) {
		return money.value;
	}

	// 使用toFixed方法将浮点数转换为字符串，保留两位小数
	return num.toFixed(2);
};
</script>

<style scope lang="scss">
.container {
	background: #f7f8fa;
	position: relative;
	color: black;
	height: 100vh;
	max-height: 100vh;
	overflow-y: hidden;
}
.content {
	padding: 20px 15px;
}
.mer {
	display: flex;
	.name {
		font-weight: 600;
		line-height: 50px;
		font-size: 20px;
	}
	.icon {
		width: 30px;
		margin: 0 auto;
	}
}
.back-icon {
	width: 40px;
	margin: 0 auto;
}
.icon-out {
	width: 50px;
	height: 50px;
	text-align: center;
	display: flex;
	flex-direction: column;
	justify-content: center;
	border-radius: 50%;
	margin-right: 10px;
}
.input {
	margin-top: 50px;
	padding: 15px;
	background: white;
	border-radius: 10px;
	display: flex;
	justify-content: space-between;
	.label {
		color: #8e8e8e;
		line-height: 50px;
	}
	.mone-icon {
		font-size: 25px;
		height: 50px;
		line-height: 65px;
	}
	.count {
		display: flex;
		.money-label {
			height: 50px;
			width: 10px;
			font-size: 25px;
		}
		.sep {
			width: 2px;
			height: 43px;
		}
	}
}
page {
	color: #fff;
	font-size: 16px;
}

.grid {
	display: grid;
	grid-gap: 1px;
	line-height: 80px;
	grid-template-columns: repeat(4, 1fr);
	color: black;
	font-size: 23px;
}

.submit {
	grid-row: 2 / span 3;
	grid-column: 4;
	color: white;
	display: flex;
	flex-direction: column;
	justify-content: center;
	.inner {
		margin: 0 auto;
		line-height: 40px;
	}
}
.zero {
	grid-column-start: 1;
	grid-column-end: 3;
}
.item {
	text-align: center;
	background-color: white;
}
.back-item {
	display: flex;
	flex-direction: column;
	justify-content: center;
}
.tapped {
	background: #aeaeae;
}
.money {
	font-size: 40px;
	font-weight: 500;
}
.top {
	position: absolute;
	z-index: 99999999;
	left: 0;
	top: 0;
	width: 100%;
	height: 300px;
	background: red;
}
.bottom {
	position: absolute;
	width: 100%;
	left: 0;
	bottom: 50px;
	.about {
		margin: 30px 10px;
		text-align: right;
	}
}
.phone {
	font-size: 12px;
	color: #000000;
	text-align: right;
	margin: 10px;
}
</style>
